package com.sj.hh.ui.blackbox.record;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bumptech.glide.Glide;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.sj.hh.R;
import com.sj.hh.picker.GlideImageLoader;
import com.sj.hh.ui.blackbox.event.VideoFilePathEvent;
import com.sj.hh.util.OkHttp3Util;
import com.sj.hh.util.SelectValueUtil;
import com.sj.hh.video.activity.AudioRecordActivity;
import com.sj.hh.video.activity.VideoRecordActivity;
import com.sj.hh.video.utils.PermissionChecker;
import com.sj.hh.video.utils.ToastUtils;
import com.sj.hh.video.view.MediaController;
import com.socks.library.KLog;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.im.server.entity.PickerType;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.BaseResponse;
import cn.rongcloud.im.server.response.RecordCommunicationResponse;
import cn.rongcloud.im.server.utils.json.JsonMananger;
import cn.rongcloud.im.ui.activity.SelectFriendsActivity;
import cn.rongcloud.im.ui.activity.base.BaseActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 添加交流记录
 */
public class AddCommunicationRecordActivity extends BaseActivity {

    private static final int RECORD_EXCHANGE_EDIT = 1;

    @BindView(R.id.tv_communication_type)
    TextView tvCommunicationType;
    @BindView(R.id.ll_communication_type)
    LinearLayout llCommunicationType;
    @BindView(R.id.edit_communication_content)
    EditText editCommunicationContent;
    @BindView(R.id.btn_file)
    Button btnFile;
    @BindView(R.id.tv_fuserid)
    TextView tvFuserid;
    @BindView(R.id.ll_fuserid)
    LinearLayout llFuserid;
    @BindView(R.id.tv_tuserid)
    TextView tvTuserid;
    @BindView(R.id.ll_tuserid)
    LinearLayout llTuserid;
    @BindView(R.id.add_image)
    ImageView addImage;
    @BindView(R.id.video)
    PLVideoTextureView video;

    private String exchangeType;
    private SharedPreferences sp;
    private String ids;
    private String fuserid;
    private String content;
    private List<String> path = new ArrayList<>();
    private GalleryConfig galleryConfig;
    private String videoFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_communication_record);
        ButterKnife.bind(this);
        setTitle("添加交流记录");

        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initView() {
        Button rightButton = getHeadRightButton();
        rightButton.setVisibility(View.GONE);
        mHeadRightText.setVisibility(View.VISIBLE);
        mHeadRightText.setText(R.string.de_save);
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sj.hh.FileProvider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();


        mHeadRightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fuserid = tvFuserid.getText().toString().trim();
                if ("30201".equals(exchangeType)) {
                    content = editCommunicationContent.getText().toString().trim();
                    updateImageFile(path);
                } else if ("30202".equals(exchangeType)) {
                    updateImageFile(path);
                } else if ("30203".equals(exchangeType) || "30204".equals(exchangeType)) {
                    ArrayList<String> videoPath = new ArrayList<>();
                    if (!TextUtils.isEmpty(videoFilePath))
                        videoPath.add(videoFilePath);//     /storage/emulated/0/ShortVideo/record.mp4
                    updateImageFile(videoPath);
                }
            }
        });

        video.setLooping(true);
        video.setAVOptions(new AVOptions());
        MediaController mediaController = new MediaController(this, true, false);
        mediaController.setOnClickSpeedAdjustListener(mOnClickSpeedAdjustListener);
        video.setMediaController(mediaController);
    }

    private MediaController.OnClickSpeedAdjustListener mOnClickSpeedAdjustListener = new MediaController.OnClickSpeedAdjustListener() {
        @Override
        public void onClickNormal() {
            // 0x0001/0x0001 = 2
            video.setPlaySpeed(0X00010001);
        }

        @Override
        public void onClickFaster() {
            // 0x0002/0x0001 = 2
            video.setPlaySpeed(0X00020001);
        }

        @Override
        public void onClickSlower() {
            // 0x0001/0x0002 = 0.5
            video.setPlaySpeed(0X00010002);
        }
    };

    private void initData() {
        sp = getSharedPreferences("config", MODE_PRIVATE);
        int userId = sp.getInt("userId", 0);
        tvFuserid.setText(userId + "");

        RecordCommunicationResponse.DataBean response = (RecordCommunicationResponse.DataBean) getIntent().getSerializableExtra("RecordCommunicationResponse");
        if (response != null) {
            setDefaultView(response);
        }
    }

    private void setDefaultView(RecordCommunicationResponse.DataBean response) {
        int type = response.getType();
        exchangeType = type + "";
        tvCommunicationType.setText(SelectValueUtil.getInstance().getMatching(SelectValueUtil.getInstance().exchangeType, exchangeType));
        tvTuserid.setText(response.getTuserid() + "");
        String content = response.getContent();
        stateShowView();
        if ("30201".equals(exchangeType)) {
            editCommunicationContent.setText(content);
        } else if ("30202".equals(exchangeType)) {
            path.add(content);
            Glide.with(mContext).load(content).into(addImage);
        } else if ("30203".equals(exchangeType)) {
            videoFilePath = content;
            playVideo(videoFilePath);
        } else if ("30204".equals(exchangeType)) {
            videoFilePath = content;
            playVideo(videoFilePath);
        }
    }

    private void playVideo(String videoFilePath) {
        video.setVideoPath(videoFilePath);
    }

    @OnClick({R.id.ll_communication_type, R.id.btn_file, R.id.ll_tuserid, R.id.add_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_tuserid:
                startActivityForResult(new Intent(this, SelectFriendsActivity.class).putExtra("isSelectFriends", true), 1);
                break;
            case R.id.ll_communication_type:
                final ArrayList<PickerType> exchangeTypes = SelectValueUtil.getInstance().getPickerData(SelectValueUtil.getInstance().exchangeType);
                showPickerView(exchangeTypes, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvCommunicationType.setText(exchangeTypes.get(options1).getValue());
                        exchangeType = exchangeTypes.get(options1).getId();
                        stateShowView();
                    }
                });
                break;
            case R.id.btn_file:
                /**
                 * 30201:文字;30202:图片;30203:声音;30204:视频
                 */
                if ("30203".equals(exchangeType)) {
                    if (isPermissionOK()) {
                        jumpToAudioCaptureActivity();
                    }
                } else if ("30204".equals(exchangeType)) {
                    if (isPermissionOK()) {
                        jumpToCaptureActivity();
                    }
                }
                break;
            case R.id.add_image:
                photoDialog();
                break;
        }
    }

    /**
     * 根据类型控件显示
     */
    private void stateShowView() {
        if ("30201".equals(exchangeType)) {
            editCommunicationContent.setVisibility(View.VISIBLE);
            btnFile.setVisibility(View.GONE);
            addImage.setVisibility(View.GONE);
            video.setVisibility(View.GONE);
        } else if ("30202".equals(exchangeType)) {
            editCommunicationContent.setVisibility(View.GONE);
            btnFile.setVisibility(View.GONE);
            addImage.setVisibility(View.VISIBLE);
            video.setVisibility(View.GONE);
        } else if ("30203".equals(exchangeType)) {
            editCommunicationContent.setVisibility(View.GONE);
            btnFile.setVisibility(View.VISIBLE);
            addImage.setVisibility(View.GONE);
            video.setVisibility(View.VISIBLE);
        } else if ("30204".equals(exchangeType)) {
            editCommunicationContent.setVisibility(View.GONE);
            btnFile.setVisibility(View.VISIBLE);
            addImage.setVisibility(View.GONE);
            video.setVisibility(View.VISIBLE);
        }
    }

    public void jumpToCaptureActivity() {
        Intent intent = new Intent(this, VideoRecordActivity.class);
        intent.putExtra(VideoRecordActivity.PREVIEW_SIZE_RATIO, "4:3");
        intent.putExtra(VideoRecordActivity.PREVIEW_SIZE_LEVEL, "720P");
        intent.putExtra(VideoRecordActivity.ENCODING_MODE, "HW");
        intent.putExtra(VideoRecordActivity.ENCODING_SIZE_LEVEL, "480x480");
        intent.putExtra(VideoRecordActivity.ENCODING_BITRATE_LEVEL, "1000Kbps");
        intent.putExtra(VideoRecordActivity.AUDIO_CHANNEL_NUM, "单声道");
        startActivity(intent);
    }

    public void jumpToAudioCaptureActivity() {
        Intent intent = new Intent(this, AudioRecordActivity.class);
        intent.putExtra(AudioRecordActivity.ENCODING_MODE, "HW");
        intent.putExtra(AudioRecordActivity.AUDIO_CHANNEL_NUM, "单声道");
        startActivity(intent);
    }

    private boolean isPermissionOK() {
        PermissionChecker checker = new PermissionChecker(this);
        boolean isPermissionOK = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checker.checkPermission();
        if (!isPermissionOK) {
            ToastUtils.s(this, "Some permissions is not approved !");
        }
        return isPermissionOK;
    }

    private Dialog dialog_photo;

    @SuppressLint("NewApi")
    private void photoDialog() {
        dialog_photo = new Dialog(this, com.rong.mbt.personal.R.style.photo_dialog);
        View view = LayoutInflater.from(this).inflate(com.rong.mbt.personal.R.layout.dialog_take_photo, null);
        dialog_photo.setContentView(view);
        Window window = dialog_photo.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(com.rong.mbt.personal.R.style.bottomDialogStyle);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        if (!dialog_photo.isShowing()) {
            dialog_photo.show();
        }
        view.findViewById(com.rong.mbt.personal.R.id.tv_open_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                } else {
                }
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(AddCommunicationRecordActivity.this);
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_choose_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                } else {
                }
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(AddCommunicationRecordActivity.this);
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog_photo.isShowing()) {
                    dialog_photo.hide();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 10) {
            ids = data.getExtras().getString("ids");
            if (!TextUtils.isEmpty(ids))
                tvTuserid.setText(ids);
        }
    }

    /**
     * 文件上传
     *
     * @param path
     */
    private void updateImageFile(List<String> path) {
        String[] uploadTaskPaths = new String[path.size()];
        for (int i = 0; i < path.size(); i++) {
            uploadTaskPaths[i] = path.get(i);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("type", exchangeType);
        map.put("fuserid", fuserid);
        map.put("tuserid", ids);
        if (!TextUtils.isEmpty(content))
            map.put("content", content);
        OkHttp3Util.uploadFile(this, OkHttp3Util.recordExchangeUrl, uploadTaskPaths, null, map, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String json = response.body().string();
                    //{"msg":"上传成功","resultCode":0}
                    BaseResponse baseResponse = JsonMananger.jsonToBean(json, BaseResponse.class);
                    KLog.e("---", "onResponse: " + json);

                    if (baseResponse.getResultCode() == 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "保存成功!!", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    finish();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {

        @Override
        public void onStart() {

        }

        @Override
        public void onSuccess(List<String> photoList) {
            path = photoList;
            if (photoList != null && photoList.size() == 1) {
                Glide.with(mContext).load(photoList.get(0)).into(addImage);
            }
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onError() {

        }
    };

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case RECORD_EXCHANGE_EDIT:
                return action.recordExchangeEdit(null, exchangeType, fuserid, ids, content);
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (video != null)
            video.stopPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (video != null)
            video.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (video != null)
            video.start();
    }

    @Subscribe
    public void onEvent(VideoFilePathEvent event) {
        if (event != null) {
            videoFilePath = event.getVideoFilePath();
            playVideo(videoFilePath);
        }
    }
}

